package br.com.basili.converter;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import javax.faces.convert.FacesConverter;

import org.apache.commons.lang3.math.NumberUtils;

import br.com.basili.dao.ResearcherDAO;
import br.com.basili.entity.Researcher;

@FacesConverter("researchConverter")
public class ResearchConverter  implements Converter  {
	
	private ResearcherDAO researcherDAO = new ResearcherDAO();

	@Override
	public Object getAsObject(FacesContext fc, UIComponent uic, String data) throws ConverterException {
		Researcher researcher = new Researcher();
		try {
			if (!NumberUtils.isNumber(data)) {
				return null;
			}
			Integer codigo = NumberUtils.createInteger(data);
			researcher = researcherDAO.getResearcherPorCodigo(codigo);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return researcher;
	}

	@Override
	public String getAsString(FacesContext fc, UIComponent ui, Object o) throws ConverterException {
		if (o == null) {
			return null;
		}
		Researcher researcher = (Researcher)o;
		return String.valueOf(researcher.getId());
	}

}
